package bean;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

public class Response {

    private OutputStream outputStream;

    private String protocol = "HTTP/1.1";
    private int statusCode = 200;
    private String msg = "OK";
    private byte[] body;
    private boolean isFirst = true;
    private Map<String, String> attributes = new HashMap<>();

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
        setAttributes("Connection","close");
        setAttributes("Content-Type", "text/html; charset=utf-8");
    }

    public void flush() throws IOException {
        this.outputStream.write(toString().getBytes());
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(protocol);
        stringBuilder.append(" ");
        stringBuilder.append(statusCode);
        stringBuilder.append(" ");
        stringBuilder.append(statusCode);
        stringBuilder.append(" \r\n");
        attributes.entrySet().forEach((e) -> {
            stringBuilder.append(e.getKey());
            stringBuilder.append(": ");
            stringBuilder.append(e.getValue());
            stringBuilder.append("\r\n");
        });
        stringBuilder.append("\r\n");
        return stringBuilder.toString();
    }

    public void setAttributes(String key, String value) {
        this.attributes.put(key, value);
    }

    public String getAttribute(String key) {
        return this.attributes.get(key);
    }

    public OutputStream getOutputStream() {
        return outputStream;
    }

    public void setOutputStream(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public String getProtocol() {
        return protocol;
    }

    public void setProtocol(String protocol) {
        this.protocol = protocol;
    }

    public int getStatusCode() {
        return statusCode;
    }

    public void setStatusCode(int statusCode) {
        this.statusCode = statusCode;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public byte[] getBody() {
        return body;
    }

    public void setBody(byte[] body) {
        this.body = body;
    }
}
